package Threads.CAS;

import java.util.concurrent.atomic.AtomicStampedReference;


//带版本号解决
public class ABA_stamped {
    static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0);
    public static void main(String[] args) throws InterruptedException {
        // 获取值 A
        String prev = ref.getReference();
        // 获取版本号
        int stamp = ref.getStamp();
        // 如果中间有其它线程干扰，发生了 ABA 现象
        Change();
        Thread.sleep(1000);
        // 尝试改为 C
        boolean b = ref.compareAndSet("A", "C", stamp, stamp + 1);

        System.out.println(b);//返回false，因为stamp不匹配
    }
    private static void Change() throws InterruptedException {
        new Thread(() -> {
            ref.compareAndSet("A","B",ref.getStamp(),ref.getStamp()+1);
        }, "t1").start();
        Thread.sleep(500);
        new Thread(() -> {
            ref.compareAndSet("B","A",ref.getStamp(),ref.getStamp()+1);
        }, "t2").start();
    }
}
